package util;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/3/18 9:30
 * @description： 所有的dao实现类的基础类
 * @modified By：
 * @version:
 */
public class BaseDao {

    static String driver = "com.mysql.jdbc.Driver";
    static String url = "jdbc:mysql://127.0.0.1:3306/db_cloudwise_5?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
    static String username = "root";
    static String password = "root";

    /**
     * 1、加载驱动
     */
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 2、获取数据库连接
     */
    public static Connection getConnection() {
        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setParameter(PreparedStatement ps, Object... params) {
        //设置占位符的参数
        if (null != params) {
            for (int i = 0; i < params.length; i++) {
                try {
                    ps.setObject(i + 1, params[i]);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param sql
     * @param params
     * @return java.lang.Boolean
     * @create by: Teacher陈（86521760@qq.com）
     * @description:3、通用的增删改方法
     * @create time: 2022/3/18 9:35
     */
    public Boolean executeUpdate(String sql, Object... params) {
        Connection connection = getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            setParameter(ps, params);
            int i = ps.executeUpdate();
            if (i > 0) {
                System.out.println("操作成功");
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭数据库连接
            closeAll(null, ps, connection);
        }
        System.out.println("操作失败");
        return false;
    }

    /**
     * @param sql
     * @param params
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @create by: Teacher陈（86521760@qq.com）
     * @description:通用的查询方法
     * @create time: 2022/3/18 10:04
     */
    public List<Map<String, Object>> executeQuery(String sql, Object... params) {

        Connection connection = getConnection();
        //创建一个集合封装所有的行数据
        List<Map<String, Object>> rowList = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            //设置占位符的参数
            setParameter(ps, params);
            //返回结果集
            resultSet = ps.executeQuery();
            //解析结果集
            ResultSetMetaData metaData = resultSet.getMetaData();
            //遍历所有的行
            while (resultSet.next()) {
                //遍历所有的列，将所有的列数据装到一个map集合中
                Map<String, Object> rowMap = new HashMap();
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    //Object value = resultSet.getObject(i + 1);
                    //获取列名
                    String key = metaData.getColumnName(i + 1);
                    //根据列名获取列值
                    Object value = resultSet.getObject(key);
                    rowMap.put(key, value);
                }
                //将一整行数据放入list集合中
                rowList.add(rowMap);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭数据库连接
            closeAll(resultSet, ps, connection);
        }
        return rowList;
    }

    /**
     * @param resultSet
     * @param ps
     * @param connection
     * @return void
     * @create by: Teacher陈（86521760@qq.com）
     * @description:关闭数据库连接
     * @create time: 2022/3/18 10:04
     */
    public void closeAll(ResultSet resultSet, PreparedStatement ps, Connection connection) {

        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != ps) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        BaseDao baseDao = new BaseDao();
       /* List<Map<String, Object>> maps = baseDao.executeQuery("select * from emp ");
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }*/
        for (int i = 0; i < 10000; i++) {
            baseDao.executeUpdate("insert into userinfo (username,password ,phone,createtime) values (?,?,?,?)","name"+i,"password"+i,100000+i,new Date());
        }
    }


}
